package com.tt.job.quartz;

import com.tt.job.api.JobContext;
import com.tt.job.api.schedule.triger.TriggerJobSchedule;
import com.tt.job.rocketmq.MqProducer;
import com.tt.job.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * quartz框架在每次调度事件到达时，新建的一个job实例
 */
public class TriggerJobEventProduceJob implements Job {
    private final static Logger logger = LoggerFactory.getLogger(TriggerJobEventProduceJob.class);

    MqProducer mqProducer;

    public TriggerJobEventProduceJob() {
        mqProducer = SpringUtils.getBean(MqProducer.class);//TODO 从spring容器中获取实例
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        boolean success = false;
        TriggerJobSchedule jobSchedule = (TriggerJobSchedule) context.getJobDetail().getJobDataMap().get("schedule");
        if (StringUtils.isEmpty(jobSchedule.getKey())) {
            jobSchedule.setKey(jobSchedule.getJobClass());
        }
        JobContext jobContext = new JobContext(jobSchedule.getJobClass(), jobSchedule);
        //补充其他context信息
        jobContext.setFireTime(context.getFireTime());
        jobContext.setNextFireTime(context.getNextFireTime());
        jobContext.setPreviousFireTime(context.getPreviousFireTime());
        jobContext.setScheduledFireTime(context.getScheduledFireTime());
        jobContext.setRetryTimes(0);
        try {
            success = mqProducer.produce(jobContext, 0);
            logger.debug("发送任务调度消息:job:{}, schedule:{}, success:{}", jobContext.getJobClass(), jobContext.getSchedule(), success);
        } catch (Exception e) {
            logger.error("将调度消息发送到消息队列失败. schedule:{}", jobSchedule, e);
        }
        if (!success) {
            //TODO 发送消息失败的情况下，需要进行重试处理（需要考虑contex.retryTime 和 context.nextFireTime）
        }
    }
}
